package com.yixing.tech.entity.entity.attr;

import com.yixing.tech.common.base.BusinessException;
import com.yixing.tech.common.base.ConditionsVO;
import com.yixing.tech.entity.entity.RequestType;
import com.yixing.tech.common.vo.s5.EntitySchema;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationOperation;

import java.util.List;
import java.util.Map;

/**
 * @author yixing tech
 * at 2021/10/9
 * describe：
 */
public final class ObjTemplate extends AttrType {
    public ObjTemplate() {
        super("对象模版", "objTemplate");
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr) throws BusinessException {
        super.out(operations, attr);
        operations.add(Aggregation.lookup("obj", attr.getCode() + ".id", "_id", attr.getCode()));
        operations.add(Aggregation.unwind(attr.getCode(), true));
    }

    @Override
    public void out(List<AggregationOperation> operations, EntitySchema.AttrVO attr, RequestType requestType) throws BusinessException {
        out(operations, attr);
    }

    /**
     * 数据插入处理
     *
     * @param source
     * @param attr
     * @return
     * @throws BusinessException
     */
    @Override
    public Object in(Object source, EntitySchema.AttrVO attr) throws BusinessException {
        if (!(source instanceof Map)) {
            Document document = new Document();
            document.put("id", new ObjectId(source.toString()));
           return document;
        }
        return super.in(source, attr);

    }

    /**
     * 过滤条件处理
     *
     * @param cond
     */
    @Override
    public void condition(ConditionsVO.Condition cond, EntitySchema.AttrVO attr) throws BusinessException{
        super.condition(cond,attr);
        if (null != cond.getValue())
            cond.setKey(cond.getKey() + ".id");
    }
}
